//
// Created by superadmin on 14-5-7.
// Copyright (c) 2014 IDongler. All rights reserved.
//


#import "ApiInvoker.h"
#import <CommonCrypto/CommonDigest.h>
#import <UIKit/UIKit.h>
#import "VMCMacros.h"

#define API_BASE_URL(url) ([NSURL URLWithString:url])


@interface ApiInvoker () <AFIdonglerApiInvokerDelegate>
@property (nonatomic, strong) AFChengShangApiInvoker *apiInvoker;
@end


@implementation ApiInvoker {

}


@synthesize apiBaseUrl = _apiBaseUrl;

@synthesize timeoutInSeconds = _timeoutInSeconds;

@synthesize signToken = _signToken;

- (id)init {
    self = [super init];
    if (self) {
        self.timeoutInSeconds = 10;
    }

    return self;
}

- (void) postApi:(NSString *)api
		andRequest:(ApiRequest *)apiRequest
		  callback:(API_CALLBACK)callback {
	[self requestApi:api WithMethod:@"POST" andRequest:apiRequest callback:callback];
}
- (void)requestApi:(NSString *)api
        WithMethod:(NSString *)httpMethod
        andRequest:(ApiRequest *)apiRequest
          callback:(API_CALLBACK)callback {

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

	//通过encodeApiRequest_iOS6: 得到请求的请求体 （参数排序、拼接成请求字符串）
    NSString *body = ([self encodeApiRequest_iOS6:apiRequest]);
    NSString *completeApiUrl = nil;
	//判断是get还是post请求 拼接成完整的请求url
    if ([self isGet:httpMethod] || [self isDelete:httpMethod]) {
        //get 和 delete方法的body放在queryString
        completeApiUrl = [NSString stringWithFormat:@"%@?%@", api, body];
    } else {
        completeApiUrl = api;
    }
    NSURL *url = [NSURL URLWithString:completeApiUrl relativeToURL:API_BASE_URL(self.apiBaseUrl)];
	NSLog(@"%@",url);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //设置超时时间:10秒
    [request setTimeoutInterval:self.timeoutInSeconds];

	//设置请求方式为传递的请求参数的方式
    [request setHTTPMethod:httpMethod];
    if ([self isPost:httpMethod] || [self isPut:httpMethod]) {
        [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    }
	//NSLog(@"%@",body);
    DLog("%@ %@ with request args (or body) \n\r%@", httpMethod, url, body);
	
	
	[self.apiInvoker request:request callback:callback];
}

- (NSString *)encodeApiRequest_iOS6:(ApiRequest *)request {
	@autoreleasepool {

		//在这个方法内对参数进行排列 然后按顺序拼接成请求的URL
		
		//ENT CS 参数算法
		NSMutableArray *namedValuePair = [[NSMutableArray alloc] init];

		NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:request.bizDataDict];
		NSString *token = [Session sharedInstance].token;
		DLog(@"现在的seseion是%@",token);
		if (NOT_NULL(token))
		{
			[dict setObject:token forKey:@"session"];
			//mobile-8563a18b338474236d5d83ad88d5478e
			//mobile-421c6b19b171120cc318ba43dd7719c4
		}
		NSArray *keys = [dict allKeys];
		DLog("keys : %@", keys);

		NSComparator comparator =  ^(id obj1, id obj2){
			NSString *key1 = obj1;
			NSString *key2 = obj2;
			return [key1 compare:key2];
		};
		NSArray *sortedKeys = [keys sortedArrayUsingComparator:comparator];
		//DLog("sortedKeys : %@", sortedKeys);

		
		NSMutableArray *values = [[NSMutableArray alloc] init];
		for(NSString *key in sortedKeys){
			NSString *value = [dict objectForKey:key];
			[values addObject:value];
			[namedValuePair addObject:[NSString stringWithFormat:@"%@=%@",key,value]];
		}
		//DLog("sortedValues : %@", sortedKeys);

		NSString *addedValues = [values componentsJoinedByString:@""];
		NSString *toSignValues = [NSString stringWithFormat:@"%@%@",addedValues,self.signToken];
		NSString *signedValues = [self md5:toSignValues];
		//DLog("sign = %@",signedValues);

		[namedValuePair addObject:[NSString stringWithFormat:@"%@=%@",@"sign",signedValues]];

		NSString *returnString = [namedValuePair componentsJoinedByString:@"&"];
		return returnString;
	}
//	mobile-f047f8d042baef0861c18c5725291043
//	mobile-f047f8d042baef0861c18c5725291043
//	2570697f11fc2eac69c72b5a7a8d7582a7d1fb98b0342d677b36d47f9e5e863a
}
- (NSString *) md5:(NSString *) input
{
	const char *cStr = [input UTF8String];
	unsigned char digest[CC_MD5_DIGEST_LENGTH];
	CC_MD5( cStr, (CC_LONG)strlen(cStr), digest ); // This is the md5 call

	NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

	for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
		[output appendFormat:@"%02x", digest[i]];

	return  output;
}
//统一处理错误
- (void)handleError:(NSInteger)statusCode response:(ApiResponse *)apiResponse {
}

- (BOOL)isGet:(NSString *)httpMethod {
    return [[httpMethod lowercaseString] isEqualToString:@"get"];
}

- (BOOL)isPut:(NSString *)httpMethod {
    return [[httpMethod lowercaseString] isEqualToString:@"put"];
}

- (BOOL)isDelete:(NSString *)httpMethod {
    return [[httpMethod lowercaseString] isEqualToString:@"delete"];
}

- (BOOL)isPost:(NSString *)httpMethod {
    return [[httpMethod lowercaseString] isEqualToString:@"post"];
}

- (void)setApiBaseUrl:(NSString *)apiBaseUrl {
	_apiBaseUrl = apiBaseUrl;
	self.apiInvoker = [AFChengShangApiInvoker apiInvokerWithBaseUrl:self.apiBaseUrl];
	self.apiInvoker.delegate = self;
}

@end